#include "history.h"
extern int history_pthread;

int history_data_upload(cJSON *root) // 上传历史数据
{
    history_pthread = 1;
    sqlite3 *db;
    char *errmsg = NULL;
    char sql[128] = "";
    if (sqlite3_open(data_db_path, &db) != SQLITE_OK) // 打开数据库
    {
        fprintf(stderr, "Database open : %s\n", sqlite3_errmsg(db));
        return -1;
    }
    // 创建表
    const char *create_table_sql = "CREATE TABLE IF NOT EXISTS data_manage (key INT, value TEXT, time long)";
    if (sqlite3_exec(db, create_table_sql, NULL, NULL, &errmsg) != SQLITE_OK)
    {
        fprintf(stderr, "Create table error: %s\n", errmsg);
        sqlite3_free(errmsg);
        sqlite3_close(db);
        return -1;
    }

    // 获取数据
    cJSON *data = cJSON_GetObjectItem(root, "data");
    if (data == NULL)
    {
        fprintf(stderr, "Failed to get 'data' from JSON.\n");
        cJSON_Delete(root);
        return -1;
    }
    int size = cJSON_GetArraySize(data);
    for (int i = 0; i < size; i++)
    {
        cJSON *item = cJSON_GetArrayItem(data, i);
        if (item == NULL)
        {
            fprintf(stderr, "Failed to get item from 'data' array.\n");
            cJSON_Delete(root);
            return -1;
        }
        cJSON *key = cJSON_GetObjectItem(item, "key");
        cJSON *value = cJSON_GetObjectItem(item, "value");
        long timestamp = time(NULL);
        if (key == NULL || value == NULL)
        {
            fprintf(stderr, "Missing 'key', 'value' or 'time' in data item.\n");
            cJSON_Delete(root);
            return -1;
        }
        // 插入数据到数据库
        snprintf(sql, sizeof(sql), 
                "INSERT INTO data_manage (key, value, time) VALUES (%d, '%s', %ld)",
                key->valueint, value->valuestring, (long)timestamp);
        if (sqlite3_exec(db, sql, NULL, NULL, &errmsg) != SQLITE_OK)
        {
            fprintf(stderr, "Insert data error: %s\n", errmsg);
            sqlite3_free(errmsg);
            cJSON_Delete(root);
            return -1;
        }
    }
    cJSON_Delete(root);
    sqlite3_close(db);
    sleep(20);
    history_pthread = 0;
    return 0;
}